﻿'
' Boogaloo® - http://www.mindfly.com
' Copyright (c) 2008-2009
' by Mindfly, Inc.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
' INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
' DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
' SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
' SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
' WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
' THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System
Imports System.IO
Imports System.Web
Imports System.Net
Imports System.Xml
Imports System.Text
Imports System.IO.Compression
Imports System.Text.RegularExpressions

Imports Boogaloo.Core.UI
Imports Boogaloo.Core.BLL

Namespace HttpHandlers

    Public Class TrackbackHandler
        Implements IHttpHandler

#Region "Private Fields"

        Private Shared ReadOnly REGEX_HTML As Regex = New Regex("</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline Or RegexOptions.Compiled)
        Private _source_has_link As Boolean

#End Region

#Region "HttpHandler"


        Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

            If Not CoreSettings.APIs("trackback").expose Then
                context.Response.StatusCode = 404
                context.Response.End()
            End If

            Dim key As String = context.Request.Params("permid")
            Dim title As String = context.Request.Params("title")
            Dim excerpt As String = context.Request.Params("excerpt")
            Dim blog_name As String = context.Request.Params("blog_name")

            Dim url As String = String.Empty
            If Not String.IsNullOrEmpty(context.Request.Params("url")) Then url = context.Request.Params("url").Split(",")(0)

            Dim source_uri As Uri = Nothing
            Try
                source_uri = New Uri(url)
            Catch ex As Exception

            End Try

            If Not String.IsNullOrEmpty(title) And Not String.IsNullOrEmpty(key) And Not String.IsNullOrEmpty(blog_name) And source_uri IsNot Nothing And key.Length = 36 Then

                Dim n As Node = GetNode(key)

                If n IsNot Nothing Then

                    ExamineSourcePage(source_uri, n.GetLink.ToString)
                    Dim contains_html As Boolean = Not String.IsNullOrEmpty(excerpt) And (REGEX_HTML.IsMatch(excerpt) Or REGEX_HTML.IsMatch(title) Or REGEX_HTML.IsMatch(blog_name))

                    If IsFirstPingBack(n, source_uri) And _source_has_link And Not contains_html Then
                        AddComment(source_uri, n, title & " - " & excerpt)
                        context.Response.Write("<?xml version=""1.0"" encoding=""iso-8859-1""?><response><error>0</error></response>")
                        context.Response.End()

                    ElseIf Not IsFirstPingBack(n, source_uri) Then

                        context.Response.Write("<?xml version=""1.0"" encoding=""iso-8859-1""?><response><error>Trackback already registered</error></response>")
                        context.Response.End()

                    ElseIf Not _source_has_link Or contains_html Then

                        context.Response.Write("<?xml version=""1.0"" encoding=""iso-8859-1""?><response><error>The source page does not link</error></response>")
                        context.Response.End()


                    End If

                End If
            ElseIf Not String.IsNullOrEmpty(key) Then
                Dim n As Node = GetNode(key)
                If n IsNot Nothing Then
                    If n.GetLink IsNot Nothing Then
                        context.Response.Redirect(n.GetLink.ToString)
                    Else
                        context.Response.Redirect(VirtualPathUtility.ToAbsolute(CoreSettings.VirtualPath))
                    End If

                End If
            Else
                context.Response.Redirect(VirtualPathUtility.ToAbsolute(CoreSettings.VirtualPath))
            End If


        End Sub

        Private Function GetNode(ByVal key As String) As Node

            Try
                Return Node.GetNodeByEntityKey(New Guid(key))
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Private Sub AddComment(ByVal source_url As Uri, ByVal n As Node, ByVal excerpt As String)
            Dim author As String = source_url.Host.Replace("www.", String.Empty)
            Dim body As String = String.Format("Trackback from {0}{1}{1}{2}", author, Environment.NewLine, Environment.NewLine, excerpt)
            Dim comment_id As Integer = Comment.InsertComment(n.entity_key, source_url.Host.Replace("www.", String.Empty), "trackback", source_url.ToString, DateTime.Now, body, True, False)
        End Sub

        ''' <summary>
        ''' Parse the HTML of the source page and look at the title
        ''' </summary>
        Private Sub ExamineSourcePage(ByVal source_uri As Uri, ByVal target_uri As String)

            Try
                Dim html As String = Groove.DownloadWebPage(source_uri)                
                _source_has_link = html.ToUpperInvariant.Contains(target_uri.ToString.ToUpperInvariant)

            Catch wex As WebException
                _source_has_link = False
            End Try

        End Sub

        ''' <summary>
        ''' Checks to see if the source has already pinged the target.
        ''' </summary>
        Private Function IsFirstPingBack(ByVal n As Node, ByVal source_url As Uri) As Boolean

            Dim c As Comment = Nothing
            For Each c In n.comments

                If String.Equals(c.website, source_url.ToString, StringComparison.OrdinalIgnoreCase) Then Return False
                If String.Equals(c.ip, HttpContext.Current.Request.UserHostAddress) Then Return False

            Next

            Return True
        End Function

        Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
            Get
                Return True
            End Get
        End Property

#End Region

    End Class


End Namespace